<template>
    <a-modal :keyboard="false" :maskClosable="false" title="跟进" :open="visible" :width="550" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="跟进途径" v-bind="validateInfos.followType">
                        <a-select
                            v-model:value="modelRef.followType"
                            :options="[
                                { label: '电话', value: 0 },
                                { label: '面谈', value: 1 },
                                { label: '信息', value: 2 },
                            ]"
                        ></a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="跟进时间" v-bind="validateInfos.followTime">
                        <a-date-picker v-model:value="modelRef.followTime" show-time placeholder="请选择跟进时间" style="width: 100%" :disabled-date="disabledDate" />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="" v-bind="validateInfos.followRecord">
                        <custom-upload v-model:fileList="modelRef.followRecord" upload-text="上传照片、视频、音频" accept="image/*,video/*,audio/*"></custom-upload>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="跟进说明" v-bind="validateInfos.followContent">
                        <a-textarea v-model:value="modelRef.followContent" show-count :maxlength="500"></a-textarea>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { cloneDeep, isEmpty, isNull } from 'lodash-es';
    import { followOrder, getOrderRecord } from '@/api/order/mine-list';
    import type { Dayjs } from 'dayjs';
    import dayjs from 'dayjs';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const lastFollowTime = ref<any>(null);
            const defaultForm = {
                followType: '',
                followTime: '',
                followContent: '',
                followRecord: [],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                followType: [{ required: true, message: '请选择' }],
                followTime: [{ required: true, message: '请选择' }],
                followContent: [{ required: true, message: '请输入' }],
                followRecord: [{ required: true, message: '请上传', type: 'array' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    const defaultTime = ref<Dayjs>(dayjs(new Date()));

                    if (props.model) {
                        if (props.model.orderProperty == 1) {
                            rulesRef.followRecord[0].required = false;
                        } else {
                            rulesRef.followRecord[0].required = true;
                        }
                        Object.assign(modelRef, {
                            orderId: props.model.id,
                            followTime: defaultTime.value,
                        });
                        getOrderRecord(props.model.id).then(res => {
                            const followList = res.data.filter(item => item.type === 6);
                            lastFollowTime.value = followList.length > 0 ? followList[followList.length - 1].content.followTime : null;
                        });
                    }
                }
            });

            const disabledDate = (current: Dayjs) => {
                // Can not select days before today and today
                if (isNull(lastFollowTime.value)) {
                    return current && current >= dayjs().endOf('day');
                } else {
                    return current && (current <= dayjs(lastFollowTime.value) || current >= dayjs().endOf('day'));
                }
            };

            // const disabledDateTime = () => {
            //     return {
            //         disabledHours: () => range(0, 24).splice(4, 20),
            //         disabledMinutes: () => range(30, 60),
            //         disabledSeconds: () => [55, 56],
            //     };
            // };

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));

                modelRef.status = 1;
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    if (dayjs(modelRef.followTime) < dayjs(props.model.orderTime)) {
                        message.error('跟进时间不能早于工单创建时间');
                        return false;
                    }
                    loading.value = true;
                    followOrder({
                        ...modelRef,
                        followTime: dayjs(modelRef.followTime).format('YYYY-MM-DD HH:mm:ss'),
                    })
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                isEmpty,

                disabledDate,
                // disabledDateTime,
            };
        },
        components: {},
    });
</script>
